import { ref } from 'vue'
import { useRequest } from '@/hooks/request'


const usePaginator = (action) => {
    const page = ref(1)

    const pageData = ref([])

    const isLoading = ref(false)

    const hasMore = ref(true)

    const loadMore = async () => {
        if (isLoading.value || !hasMore.value) return

        isLoading.value = true

        try {
            const result = await useRequest(action, {
                query: {
                    page: page.value,
                }
            })

            if (result.data.length == 0) hasMore.value = false

            pageData.value.push(...result.data)

            page.value++

        } catch (error) {
            throw new Error(error)
        } finally {
            isLoading.value = false
        }
    }

    return {
        page,
        pageData,
        isLoading,
        hasMore,
        loadMore
    }
}

export {
    usePaginator
}